#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <pthread.h>
#include "thread.hpp"

using namespace ThreadModule;
int sockfd;
std::string server_ip;
uint16_t server_port = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void Recv()
{
    while (1)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);

        buffer[m] = 0;
        std::cerr << buffer << std::endl;
    }

    // inet 127.0.0.1 本地环回
}

void Send()
{
    // 1.填写客户端的端口信息
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    while (1)
    {
        std::string input;
        std::cout << "please enter@";
        std::getline(std::cin, input);

        int n = sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            std::cout << "sendto fail" << std::endl;
            exit(1);
        }
    }
}

void *readmessage(void *args)
{

    return nullptr;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " ip port" << std::endl;
        exit(1);
    }
    server_ip = argv[1];
    server_port = std::stoi(argv[2]);

    // 创建套接字
    sockfd = socket(AF_INET, SOCK_DGRAM, 0); // 表示通过ipv4协议创建一个面向数据报套接字
    if (sockfd < 0)
    {
        std::cout << "创建套接字失败" << std::endl;
        exit(1);
    }

    // 本地的ip和端口和上面的“文件”关联
    // 客户端要绑定，但是不需要显示的绑定，在首次绑定的时候会由操作系统随机绑定
    // 为了防止端口冲突

    // 2.创建线程
    Thread recver(Recv);
    Thread sender(Send);

    recver.Start();
    sender.Start();

    recver.Join();
    recver.Join();

    while (true)
    {
    }
    return 0;
}